package com.newflypig.jblog.controller.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextImpl;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

public class AdminPostInterceptor implements HandlerInterceptor{

	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		if("POST".equalsIgnoreCase(request.getMethod())){
			SecurityContextImpl sci = (SecurityContextImpl)request.getSession().getAttribute("SPRING_SECURITY_CONTEXT");
			for(GrantedAuthority ga : sci.getAuthentication().getAuthorities()){
				if("ROLE_ADMIN".equals(ga.getAuthority()))
					return true;
			}
			response.setStatus(403);	//403:forbidden
			return false;
		}
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
	}

	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
	}

}
